package com.tatada.mvvmdemo.net;

import android.text.TextUtils;

import com.toshi.netlib.api.BaseResponse;
import com.toshi.netlib.base.NetworkApi;
import com.toshi.netlib.errorhandler.ExceptionHandle;

import io.reactivex.functions.Function;
import okhttp3.Interceptor;

public class TestNetApi extends NetworkApi {

    private static volatile TestNetApi instance;

    public static TestNetApi getInstance() {
        if (instance == null) {
            synchronized (TestNetApi.class) {
                if (instance == null) {
                    instance = new TestNetApi();
                }
            }
        }
        return instance;
    }

    public static <T> T getService(Class<T> service) {
        return getInstance().getRetrofit(service).create(service);
    }


    @Override
    protected Interceptor getInterceptor() {
        return null;
    }

    @Override
    protected <T> Function<T, T> getAppErrorHandler() {
        return new Function<T, T>() {
            @Override
            public T apply(T response) throws Exception {
                if (response instanceof BaseResponse && ((BaseResponse) response).getCode() == 0) {
                    ExceptionHandle.ServerException exception = new ExceptionHandle.ServerException();
                    exception.code = ((BaseResponse) response).getCode();
                    exception.message = TextUtils.isEmpty(((BaseResponse) response).getMsg()) ? "hhhhhh" : ((BaseResponse) response).getMsg();
                    throw exception;
                }
                return response;
            }
        };
    }

    @Override
    public String getFormal() {
        return "";
    }

    @Override
    public String getTest() {
        return "http://192.168.3.103:9001/android/";
    }
}
